<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/17
 * Time: 11:37
 */

namespace app\admin\controller;

use think\Db;

/**
 * Class Commodity
 * @package app\admin\controller 商品管理
 */
class Commodity extends Base
{

    public function index()
    {

        $num = Db::name('photo')
            ->alias('p')
            ->join('edd_user u', 'u.id = p.uid')
            ->count();
        $pageObject = new \Page($num);

        $list = Db::name('photo')
            ->alias('p')
            ->join('edd_user u', 'u.id = p.uid')
            ->field('u.name as username,p.*')
            ->select();

        $map = array(
            'num' => $num,
            'page' => $pageObject->showPages(),
            'list' => $list
        );

        return view('index', $map);

    }

    public function edit()
    {
        if ($_POST) {
            $data = $_POST;
            $info = Db::name('photo')->update($data);
            if ($info) {
                $this->success('编辑成功！');
            } else {
                $this->error('编辑失败！');
            }
        } else {
            $id = input('id');
            $list = Db::name('photo')
                ->alias('p')
                ->field('p.*,u.name as username,a.name as aname')
                ->join('edd_user u','u.id = p.uid')
                ->join('edd_album a','a.id = p.album_id')
                ->where(array('p.id'=>$id))
                ->find();

            $map = array(
                'list'=>$list
            );

            return view('edit',$map);
        }

    }

    /**
     * 照片删除
     */
    public function del()
    {
        $ids = input('id');
        $img = Db::name('photo')->where(array('id' => $ids))->find();
        $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $img['img_url'];

        array_map("unlink", glob($path));

        if (!count(glob($path))) {

            if (!Db::name('photo')->where(array('id' => $img['id']))->delete()) {

                $this->error('删除失败！');

            } else {

                $this->error('删除成功！');

            }

        } else {

            $this->error('删除失败！');

        }

    }

}